import { login, logout, getInfo, refreshToken, getDepInfo, changeWorkingDep } from '@/api/user'

import { getToken, getRefreshToken, setToken, removeAllToken } from '@/utils/auth'
import store from '../index'

const getDefaultState = () => {
  return {
    token: getToken(),
    refreshToken: getRefreshToken(),
    userid: '',
    defDepId: '', // 默认组织id
    name: '', // 用户名（登录名）
    userName: '', // 显示名称
    avatar: '',
    deps: new Map(),
    expSeconds: 3600 // 默认过期时间 秒数
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token, refreshToken) => {
    state.token = token
    state.refreshToken = refreshToken
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USER_NAME: (state, userName) => {
    state.userName = userName
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // 设置 用户 的组织信息
  SET_DEPS: (state, deps) => {
    state.deps = deps
  },
  // 设置用户的 默认组织信息
  SET_DEF_DEP_ID: (state, defDepId) => {
    state.defDepId = defDepId
  }
}

let refreshLock = false // 加了一把刷新锁
const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, imageCode } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, imageCode: imageCode }).then(response => {
        if (response.code === '200') {
          const { data } = response
          commit('SET_TOKEN', data.access_token, data.refresh_token)
          setToken(data.access_token, data.refresh_token, data.expires_in)
          resolve()
        } else {
          reject(response.msg)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          // reject('获取用户信息失败，请重新登录！')
          console.log('获取用户信息为空')
        } else {
          const { userName, loginName, currentDepId } = data
          commit('SET_NAME', loginName)
          commit('SET_USER_NAME', userName)
          commit('SET_DEF_DEP_ID', currentDepId)
          // commit('SET_AVATAR', avatar)
          resolve(data)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取登录用户的组织信息
  getDepInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getDepInfo().then(response => {
        const { data } = response
        if (!data) {
          // reject('获取用户信息失败，请重新登录！')
          // console.log('获信息为空')
        } else {
          commit('SET_DEPS', data)
          resolve(data)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  changeWorkingDep({ commit }, depId) {
    return new Promise((resolve, reject) => {
      changeWorkingDep(depId).then(response => {
        const { data } = response
        if (!data) {
          // reject('获取用户信息失败，请重新登录！')
          // console.log('获信息为空')
        } else {
          commit('SET_DEPS', data)
          commit('SET_DEF_DEP_ID', depId)
          resolve(data)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeAllToken() // must remove  token  first
        // resetRouter() // 放在了下面的方法里面
        store.dispatch('menu/resetMenus') // 清除权限路由和重置路由
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('RESET_STATE')
      removeAllToken() // must remove  token  first
      store.dispatch('menu/resetMenus') // 清除权限路由和重置路由
      resolve()
    })
  },

  // 刷新token
  refreshToken({ commit }) {
    return new Promise((resolve, reject) => {
      // 加了一把刷新锁， 防止重复刷新，后台一个token支持刷新一次
      if (!refreshLock) {
        refreshLock = true
        if (!getRefreshToken()) {
          refreshLock = false
          reject('登录已过期，请重新登录')
        } else {
          refreshToken({ grant_type: 'refresh_token', refresh_token: getRefreshToken(), access_token: getToken() }).then(response => {
            if (response.code === '200') {
              const { data } = response
              commit('SET_TOKEN', data.access_token, data.refresh_token)
              setToken(data.access_token, data.refresh_token, data.expires_in)
              refreshLock = false
              resolve()
            } else {
              store.dispatch('user/resetToken')
              resolve(response)
            }
          }).catch(error => {
            store.dispatch('user/resetToken')
            reject(error)
          })
        }
      } else {
        resolve({})
      }
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

